﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DMS.Business.Modules.ArchivesManagement;
using DMS.Data;
using DMS.Data.Modules.Statistics;
using DMS.Business.Modules.Statistics;
using System.Data;
using System.Text;
using InfoSoftGlobal;
using DMS.Business.Utility;

namespace DMS.Web.Modules.Statistics
{
    public partial class StatArchInfo : System.Web.UI.Page
    {
        #region 属性

        private List<DeliveryData> DeliveryDataList
        {
            get
            {
                return ViewState["DeliveryDataList"] as List<DeliveryData>;
            }
            set
            {
                ViewState["DeliveryDataList"] = value;
            }
        }

        #endregion

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                InitControls();
                Stat();
            }
        }

        private void InitControls()
        {
            //默认显示当前月
            //txtBeginInitialTime.Text = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1).ToString("yyyy-MM-dd");

            if (!SystemContext.Current.LoginUser.IsInRole("档案管理员;系统管理员;"))
            {
                this.destoryBtn.Visible = false;

                archInfoList.Columns[12].Visible = false;
            }
        }

        protected string GetCondition()
        {
            string condition = "";

            condition += " and it.Type is not null";

            if(ddlBelongYear.SelectedValue!="")
            {
                condition += string.Format(" and it.BelongYear = '{0}'", ddlBelongYear.SelectedValue);
            }
            if(ddlBelongMonth.SelectedValue!="")
            {
                condition += string.Format(" and it.BelongMonth = '{0}'", ddlBelongMonth.SelectedValue);
            }
            if (txtName.Text != "")
            {
                condition += string.Format(" and it.Name like '%{0}%'", txtName.Text.Trim());
            }
            if (txtType.SelectedValue != "")
            {
                condition += string.Format(" and it.Type = '{0}'", txtType.SelectedValue);
            }
            if (txtInitDateBegin.Text != "")
            {
                condition += string.Format(" and it.InitDate >= cast('{0}' as System.DateTime)", DateTime.Parse(txtInitDateBegin.Text));
            }
            if (txtInitDateEnd.Text != "")
            {
                condition += string.Format(" and it.InitDate <= cast('{0}' as System.DateTime)", DateTime.Parse(txtInitDateEnd.Text));
            }
            if (txtBeginTimeBegin.Text != "")
            {
                condition += string.Format(" and it.CustodyBeginDate >= cast('{0}' as System.DateTime)", DateTime.Parse(txtBeginTimeBegin.Text));
            }
            if (txtBeginTimeEnd.Text != "")
            {
                condition += string.Format(" and it.CustodyBeginDate <= cast('{0}' as System.DateTime)", DateTime.Parse(txtBeginTimeEnd.Text));
            }
            if (txtExpireTimeBegin.Text != "")
            {
                condition += string.Format(" and it.CustodyEndDate >= cast('{0}' as System.DateTime)", DateTime.Parse(txtExpireTimeBegin.Text));
            }
            if (txtExpireTimeEnd.Text != "")
            {
                condition += string.Format(" and it.CustodyEndDate <= cast('{0}' as System.DateTime)", DateTime.Parse(txtExpireTimeEnd.Text));
            }
            if (txtPersonName.Text != "")
            {
                condition += string.Format(" and it.PersonName like '%{0}%'", txtPersonName.Text.Trim());
            }
            if (ddlDestroy.SelectedValue != "")
            {
                condition += string.Format(" and it.IsDestroy = {0}", ddlDestroy.SelectedValue);
            }
            if (ddlIsExpire.SelectedValue != "")
            {
                if(ddlIsExpire.SelectedValue=="True")
                {
                    condition += string.Format(" and it.CustodyEndDate <= cast('{0}' as System.DateTime)", DateTime.Now);
                }else
                {
                    condition += string.Format(" and (it.CustodyEndDate > cast('{0}' as System.DateTime) or it.CustodyYear=0 )", DateTime.Now);
                }
            }

            return condition;
        }

        
        protected void DealCommand(object sender, GridViewCommandEventArgs e)
        {
            string commandName = e.CommandName;
            var id = e.CommandArgument as string;
            if (commandName.Equals("DeleteArchInfo"))
            {
                ArchInfoService.DeleteArchInfo(id);
            }
            Stat();
        }

        private void Stat()
        {
            int total;
            string condition = GetCondition();
           
            if (this.PageSize.Text == "")
                this.PageSize.Text = "15";
            pager.PageSize = int.Parse(this.PageSize.Text);
            List<AM_ArchivesInfo> list = ArchInfoService.GetArchInfos(SystemContext.Current.LoginAuthUser, condition,
                                                                  pager.CurrentPageIndex, pager.PageSize, out total);

            // 获取GridView排序数据列及排序方向
            string sortExpression = this.archInfoList.Attributes["SortExpression"];
            string sortDirection = this.archInfoList.Attributes["SortDirection"];

            IQueryable<AM_ArchivesInfo> queryableList;
            // 根据GridView排序数据列及排序方向设置显示的默认数据视图
            if ((!string.IsNullOrEmpty(sortExpression)) && (!string.IsNullOrEmpty(sortDirection)))
            {
                //调用排序方法对当前页数据进行排序
                queryableList = (list.AsQueryable()).OrderUsingSortExpression(sortExpression + " " + sortDirection);
            }
            else
            {
                queryableList = list.AsQueryable();
            }

            // GridView绑定并显示数据
            this.archInfoList.DataSource = queryableList;
            this.archInfoList.DataBind();

            pager.RecordCount = total;
        }

        //列表的排序事件
        protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
        {
            // 从事件参数获取排序数据列
            string sortExpression = e.SortExpression.ToString();
            // 假定为排序方向为“顺序”
            string sortDirection = "ASC";
            // “ASC”与事件参数获取到的排序方向进行比较，进行GridView排序方向参数的修改
            if (sortExpression == archInfoList.Attributes["SortExpression"])
            {
                //获得下一次的排序状态
                sortDirection = (archInfoList.Attributes["SortDirection"].ToString() == sortDirection ? "DESC" : "ASC");
            }
            // 重新设定GridView排序数据列及排序方向
            archInfoList.Attributes["SortExpression"] = sortExpression;
            archInfoList.Attributes["SortDirection"] = sortDirection;
            
            Stat();
        }

        /// <summary>
        /// 翻页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void pager_PageChanged(object sender, EventArgs e)
        {
            Stat();
        }


        protected void btnStat_Click(object sender, EventArgs e)
        {
            Stat();
        }

        protected void gvList_RowDataBound(object sender, GridViewRowEventArgs e)
        {

        }

        protected void gvList_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            archInfoList.PageIndex = e.NewPageIndex;
            Stat();
        }

        protected void ExportClick(object sender, EventArgs e)
        {
            string condition = GetCondition();

            Dictionary<string, DataTable[]> forms = new Dictionary<string, DataTable[]>();
            List<DataTable> tables = ArchInfoService.GetArchInfoTable(SystemContext.Current.LoginAuthUser, condition);
            
            if(tables==null)
            {
                ClientHelper.Instance.Alert("导出记录数超过Excel的最大行数（65535），请先筛选数据，分多次导出，谢谢。");
                return;
            }

            forms.Add("档案资料信息", tables.ToArray());
            try
            {
                ClientHelper.Instance.ExportToExcel(forms, "档案资料信息");
            }catch(Exception ex)
            {
                LogHelper.LogException(ex);
            }
            
        }

    }
}